package com.tanhua.server.controller;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.common.vo.PageResult;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.Ttype;
import com.tanhua.server.service.QuanZiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author LOVE
 */
@RestController
@RequestMapping("comments")
public class CommentController {

    @Autowired
    private QuanZiService quanZiService;

    /**
     * 查询评论数
     *
     * @param movementId 动态ID
     * @param page  当前页
     * @param pagesize 每页条数
     */
    @GetMapping
    public ResponseEntity<?> comments(String movementId, Integer page, Integer pagesize) {
        PageResult comments = quanZiService.findComments(movementId, page, pagesize);
        if (ObjectUtil.equal(comments, null)) {
            return ResponseEntity.ok("未能获取到评论信息!");
        }
        return ResponseEntity.ok(comments);

    }
    
    /**
     * 评论
     *
     * @param map
     * @param
     */
    @PostMapping
    public ResponseEntity<?> commentsSubmit(@RequestBody Map<String, String> map) {
        return quanZiService.commentsSubmit(map.get("movementId"), map.get("comment"));
    }

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    @GetMapping("/{id}/like")
    public ResponseEntity<Long> likeComment(@PathVariable("id") String publishId) {
        //指定类型为点赞
        CommentType commentType = CommentType.LIKE;
        //指定类型为添加
        Ttype tType = Ttype.INSERT;

        return getLongResponseEntity(publishId, commentType, tType);
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */

    @GetMapping("/{id}/dislike")
    public ResponseEntity<Long> rmLikeComment(@PathVariable("id") String publishId) {
        //指定类型为点赞
        CommentType commentType = CommentType.LIKE;
        //指定类型为添加
        Ttype tType = Ttype.REMOVE;

        return getLongResponseEntity(publishId, commentType, tType);
    }

    /**
     * 根据类型进行点赞喜欢或取消
     *
     * @param publishId
     * @param commentType
     * @param tType
     * @return
     */

    private ResponseEntity<Long> getLongResponseEntity(String publishId, CommentType commentType, Ttype tType) {
        try {
            //进行点赞或喜欢,并获取点赞数和喜欢数
            Long likeCount = quanZiService.arbitrarilyComment(publishId, commentType, tType);
            if (likeCount != null) {
                return ResponseEntity.ok(likeCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
